package com.itclass.auth.authentication.adapter.support;

import com.itclass.auth.authentication.adapter.AbstractAuthenticationAdapter;
import com.itclass.auth.authentication.token.supprt.UsernamePasswordLoginAuthenticationToken;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class UsernamePasswordAuthenticationAdapter extends AbstractAuthenticationAdapter<HttpServletRequest, UsernamePasswordLoginAuthenticationToken> {


    protected AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
    private String usernameParameter= "username";
    private String passwordParameter ="password";

    public UsernamePasswordAuthenticationAdapter() {
        super("username");
    }
    @Override
    public boolean supports(String loginTypeName) {
        return this.getLoginType().equals(loginTypeName);
    }


    @Override
    public UsernamePasswordLoginAuthenticationToken handle(HttpServletRequest request) {
        String username = obtainUsername(request);
        username = (username != null) ? username.trim() : "";
        String password = obtainPassword(request);
        password = (password != null) ? password : "";
        UsernamePasswordLoginAuthenticationToken authRequest = new UsernamePasswordLoginAuthenticationToken(false);
        authRequest.setPrincipal(username);
        authRequest.setCredentials(password);
        return authRequest;
    }

    private void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }


    @Nullable
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(this.passwordParameter);
    }

    /**
     * Enables subclasses to override the composition of the username, such as by
     * including additional values and a separator.
     * @param request so that request attributes can be retrieved
     * @return the username that will be presented in the <code>Authentication</code>
     * request token to the <code>AuthenticationManager</code>
     */
    @Nullable
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(this.usernameParameter);
    }
}
